#coding:utf-8
import logging
import os
import traceback

#日志文件名
LOG_FILE_NAME='download.log'
#日志文件目录
LOG_PATH = os.path.join(os.path.dirname(__file__), 'log')

#日志文件保存全路径
FULL_LOG_PATH = os.path.join(LOG_PATH, LOG_FILE_NAME)
# FULL_LOG_PATH = '/home/zero/file/abc/日志/mylog.log'

dir_name, file_name = os.path.split(FULL_LOG_PATH)
#日志文件目录不存在创建目录
if not os.path.exists(dir_name):
    os.makedirs(dir_name)

#日志内容格式化
formatter_str = '[%(levelname)5s][%(asctime)s][%(process)d][%(filename)s:%(lineno)d][%(funcName)s] %(message)s'
LOG = logging.getLogger()
#记录日志到文件
hdlr = logging.FileHandler(FULL_LOG_PATH, 'a+')
print('日志文件保存路径:%s' % FULL_LOG_PATH)
#控制台打印
consoleHdlr = logging.StreamHandler()
formatter = logging.Formatter(formatter_str)
hdlr.setFormatter(formatter)
consoleHdlr.setFormatter(formatter);
LOG.addHandler(hdlr)
LOG.addHandler(consoleHdlr)
#设置日志级别
LOG.setLevel(logging.INFO)

def debug(*msg):
    '''
        debug日志记录方法
    '''
    _info = _fmtInfo(msg)
    try:
        LOG.debug(_info)
    except:
        print 'mylog debug:' + _info
        
def info(*msg):
    '''
        info日志记录方法
    '''
    _info = _fmtInfo(msg)
    try:
        LOG.info(_info)
    except:
        print 'mylog info:' + _info
            
def warn(*msg):
    '''
        warn日志记录方法
    '''
    _info = _fmtInfo(msg)
    try:
        LOG.warn(_info)
    except:
        print 'mylog warning:' + _info
        
def error(*msg):
    '''
        error日志记录方法
    '''
    _info = _fmtInfo(msg)
    try:
        LOG.error(_info)
    except:
        print 'mylog error:' + _info

def _fmtInfo(msg):
    '''
        格式化日志内容
    '''
    if len(msg) == 0:
        return _trace_exception_info()
    else:
        _tmp = [msg[0]]
        if _trace_exception_info() != '':
            _tmp.append(_trace_exception_info()) 
        return '\n'.join(_tmp)


def _trace_exception_info():
    '''
        获取异常信息
    '''
    if traceback.format_exc() == 'None\n':
        return ''
    else:
        return traceback.format_exc()
